package com.gyx.lottery.service.impl;

import cn.hutool.core.lang.UUID;
import com.gyx.lottery.common.errorcode.ServiceErrorCodeConstants;
import com.gyx.lottery.common.exception.ServiceException;
import com.gyx.lottery.service.PictureService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Service
public class PictureServiceImpl implements PictureService {
    @Value("${pic.local-path}")
    private String localFilePath;
    @Override
    public String savePicture(MultipartFile file) {
    //创建目录
        File dir=new File(localFilePath);
        if(!dir.exists()){
            dir.mkdirs();
        }
    //创建图片索引
        String fileName=file.getOriginalFilename();
        assert fileName!=null;
        String suffix=fileName.substring(
                fileName.lastIndexOf("."));
        fileName= UUID.randomUUID()+suffix;
    try{
        file.transferTo(new File(localFilePath+"/"+fileName));
    }
    catch (IOException e){
    throw new ServiceException(ServiceErrorCodeConstants.PICTURE_UPLOAD_ERROR);
    }
        return fileName;
    }
}
